<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" destroy-on-close @closed="$emit('closed')" fullscreen :close-on-press-escape="mode != 'show' ? false : true">
		<el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="120px" label-position="right">
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="销售单号" prop="contract_code">
                        <el-input v-model="form.contract_code" placeholder="销售单号(不填写自动生成)" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="销售日期" prop="open_single">
                        <el-date-picker v-model="form.open_single" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="销售人员" prop="seller_id">
                        <el-select v-model="form.seller_id" filterable clearable placeholder="请选择销售人员" style="width:100%">
                            <el-option v-for="item in adminList" :key="item.id" :label="item.name" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-col :span="24">
                <el-form-item label="产品清单" prop="order_detail">
                    <!-- <el-button type="primary" size="small" icon="el-icon-plus" @click="checkGoods">选择商品</el-button> -->
                    <sc-form-table ref="table" v-model="order_detail" :addTemplate="addTemplate" placeholder="暂无数据" height="650">
                        <el-table-column prop="goods_model" label="产品型号" align="center" width="180">
                            <template #default="scope">
                                <el-select v-model="scope.row.goods_model" filterable placeholder="请选择产品" style="width:100%" @change="goodsChange(scope.row)">
                                    <el-option v-for="item in goodsList" :key="item.name" :label="item.name" :value="item.name"/>
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column prop="speed_ratio_id" label="速比" align="center" width="150">
                            <template #default="scope">
                                <el-select v-model="scope.row.speed_ratio_id" filterable clearable style="width: 100%" placeholder="请选择速比" @change="speedChange(scope.row)">
                                    <el-option v-for="item in scope.row.speedList" :key="item.id" :label="item.name" :value="item.id" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column prop="flange_id" label="法兰" align="center" width="150">
                            <template #default="scope">
                                <el-select v-model="scope.row.flange_id" filterable clearable style="width: 100%" placeholder="请选择法兰" @change="flangeChange(scope.row)">
                                    <el-option v-for="item in scope.row.flangeList" :key="item.id" :label="item.name" :value="item.id" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column prop="color_id" label="颜色" align="center" width="150">
                            <template #default="scope">
                                <el-select v-model="scope.row.color_id" filterable clearable style="width: 100%" placeholder="请选择颜色" @change="colorChange(scope.row)">
                                    <el-option v-for="item in scope.row.colorList" :key="item.id" :label="item.name" :value="item.id" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="孔数" prop="hole" align="center" width="150">
                            <template #default="scope">
                                <el-input v-model="scope.row.hole" placeholder="孔数" ></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="数量" prop="sale_num" align="center" width="100">
                            <template #default="scope">
                                <el-input v-model="scope.row.sale_num" placeholder="数量" @input="totalCompute"></el-input>
                                 <!-- @focus="onFocus($event)" -->
                            </template>
                        </el-table-column>
                        <el-table-column label="单价" prop="price" align="center" width="100">
                            <template #default="scope">
                                <el-input v-model="scope.row.price" placeholder="单价" @input="totalCompute"></el-input>
                                 <!-- @focus="onFocus($event)" -->
                            </template>
                        </el-table-column>
                        <el-table-column label="小计" prop="total_price" align="center" width="120">
                            <template #default="scope">
                                <el-input v-model="scope.row.total_price" placeholder="小计" readonly></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="客户" prop="customer_id" align="center" width="130">
                            <template #default="scope">
                                <el-select v-model="scope.row.customer_id" filterable style="width: 100%" placeholder="请选择客户">
                                    <el-option v-for="item in clientList" :key="item.id" :label="item.customer_name" :value="item.id" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="备注1" prop="remark1" align="center">
                            <template #default="scope">
                                <el-input v-model="scope.row.remark1" placeholder="备注1" @input="remarkInput(scope.row)" type="textarea" :rows="3"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="备注2" prop="remark2" align="center">
                            <template #default="scope">
                                <el-input v-model="scope.row.remark2" placeholder="备注2" type="textarea" :rows="3"></el-input>
                            </template>
                        </el-table-column>
                    </sc-form-table>
                </el-form-item>
            </el-col>
            <!-- <el-row :gutter="1">
				<el-col :span="6">
					<el-form-item label="总金额" prop="total_price">
						<el-input v-model="form.total_price" placeholder="总金额" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="结算账户" prop="settlement_id">
						<el-select v-model="form.settlement_id" filterable clearable placeholder="请选择账户" style="width:100%">
							<el-option v-for="item in accountList" :key="item.id" :label="item.account" :value="item.id"/>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="收款金额" prop="pay_price">
						<el-input v-model="form.pay_price" placeholder="收款金额" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="是否分期" prop="is_stages">
						<el-switch v-model="form.is_stages" :active-value="1" :inactive-value="0" inline-prompt active-text="分期" inactive-text="不分期"></el-switch>
						<el-tag type="primary" v-if="form.is_stages == 1" @click="openStage">设置收款金额</el-tag>
					</el-form-item>
				</el-col>
			</el-row> -->
        </el-form>
        <el-footer style="text-align: right;position: fixed;bottom: 0;right: 0;left: 0;padding: 10px 20px;background: #fff;border-top: 1px solid #eee;">
            <el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit(0)">保存</el-button>
			<el-button v-if="mode == 'add'" type="primary" :loading="isSaveing" @click="submit(1)">保存并审核</el-button>
        </el-footer>
	</el-dialog>
    <select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsUpdate" @closed="dialog.goods=false" :query="{get_product:1}"></select-goods>
    <!-- <el-dialog title="设置分期收款" v-model="stage" :close-on-click-modal="false" :close-on-press-escape="false">
		<el-form :disabled="mode == 'show'">
			<sc-form-table ref="table" v-model="stages_all" :addTemplate="addTemplate" placeholder="暂无数据" height="550" hideAdd hideDelete>
				<el-table-column prop="type" label="期别" align="center" width="100">
					<template #default="scope">
						<div v-for="item in stages_all" :key="item.stages_number">
							{{ scope.row.stages_number == item.stages_number ? item.type : '' }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="收款百分比" prop="collect_rate" align="center">
					<template #default="scope">
						<el-input-number type="number" v-model="scope.row.collect_rate" placeholder="收款百分比" @change="stageInputRate(scope.row,scope.$index)"
										 controls-position="right">
							<template #suffix>
								<span>%</span>
							</template>
						</el-input-number>
					</template>
				</el-table-column>
				<el-table-column label="收款金额" prop="money" align="center">
					<template #default="scope">
						<el-input-number type="number" v-model="scope.row.money" placeholder="收款金额" @change="stageInput(scope.row,scope.$index)"
										 controls-position="right"></el-input-number>
					</template>
				</el-table-column>
				<el-table-column label="款项日期" prop="collect_date" align="center">
					<template #default="scope">
						<el-date-picker v-model="scope.row.collect_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%"/>
					</template>
				</el-table-column>
				<el-table-column label="备注" prop="remark" align="center">
					<template #default="scope">
						<el-input v-model="scope.row.remark" placeholder="备注"></el-input>
					</template>
				</el-table-column>
			</sc-form-table>
		</el-form>
		<template #footer>
			<el-button @click="stage = false">取消</el-button>
			<el-button type="primary" v-if="mode != 'show'" @click="closeStage">确定</el-button>
		</template>
	</el-dialog> -->
</template>

<script>
import selectGoods from '../../goods/info/selectGoods.vue';
export default {
    components: { selectGoods },
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '新增销售订单',
				edit: '编辑销售订单',
				show: '查看'
			},
			visible: false,
			isSaveing: false,
			//表单数据
			form: {
                id: "",
                seller_id: this.$TOOL.data.get("USER_INFO").admin_id,
                contract_code: "",
                open_single: this.moment().format('YYYY-MM-DD'),
                customer_id: '1',
                contacts: '1',
                contract_price: "",
                // total_price: "",
				// pay_price: 0,
				// settlement_id: "",
				// is_stages: 0,
				// stages_all: [],
                is_check: 0,
			},
			//验证规则
			rules: {
				// customer_id: [{ required: true, message: '请选择客户' }],
				// contacts: [{ required: true, message: '请选择联系人' }],
			},
            contactList: [],
            unitList: [],
            adminList: [],
            speedList: [],
            flangeList: [],
            colorList: [],
            clientList: [],
            addTemplate:{sale_num: 1,goods_model: '',speed_ratio_id: '',flange_id: '',color_id: '',price: '',customer_id: ''},
            dialog:{
                goods: false,
            },
            order_detail:[],
            // stage: false,
			// stages_all: [
			// 	{
			// 		stages_number: 1,
			// 		type: '首期金额',
			// 		collect_rate: 100,
			// 		money: 0,
			// 		collect_date: this.moment().format('YYYY-MM-DD'),
			// 		remark: ""
			// 	},
			// 	{
			// 		stages_number: 2,
			// 		type: '二期金额',
			// 		collect_rate: 0,
			// 		money: 0,
			// 		collect_date: "",
			// 		remark: ""
			// 	},
			// 	{
			// 		stages_number: 3,
			// 		type: '三期金额',
			// 		collect_rate: 0,
			// 		money: 0,
			// 		collect_date: "",
			// 		remark: ""
			// 	},
			// 	{
			// 		stages_number: 4,
			// 		type: '四期金额',
			// 		collect_rate: 0,
			// 		money: 0,
			// 		collect_date: "",
			// 		remark: ""
			// 	},
			// 	{
			// 		stages_number: 5,
			// 		type: '五期金额',
			// 		collect_rate: 0,
			// 		money: 0,
			// 		collect_date: "",
			// 		remark: ""
			// 	},
			// 	{
			// 		stages_number: 6,
			// 		type: '六期金额',
			// 		collect_rate: 0,
			// 		money: 0,
			// 		collect_date: "",
			// 		remark: ""
			// 	},
			// 	{
			// 		stages_number: 7,
			// 		type: '七期金额',
			// 		collect_rate: 0,
			// 		money: 0,
			// 		collect_date: "",
			// 		remark: ""
			// 	},
			// 	{
			// 		stages_number: 8,
			// 		type: '八期金额',
			// 		collect_rate: 0,
			// 		money: 0,
			// 		collect_date: "",
			// 		remark: ""
			// 	},
			// 	{
			// 		stages_number: 9,
			// 		type: '九期金额',
			// 		collect_rate: 0,
			// 		money: 0,
			// 		collect_date: "",
			// 		remark: ""
			// 	},
			// 	{
			// 		stages_number: 10,
			// 		type: '十期金额',
			// 		collect_rate: 0,
			// 		money: 0,
			// 		collect_date: "",
			// 		remark: ""
			// 	},
			// 	{
			// 		stages_number: 11,
			// 		type: '十一期金额',
			// 		collect_rate: 0,
			// 		money: 0,
			// 		collect_date: "",
			// 		remark: ""
			// 	},
			// 	{
			// 		stages_number: 12,
			// 		type: '十二期金额',
			// 		collect_rate: 0,
			// 		money: 0,
			// 		collect_date: "",
			// 		remark: ""
			// 	},
			// ],
            accountList: [],
		}
	},
	mounted() {
        this.getCate()  //分类
        this.getUnit() // 单位
        this.getAdmin()
        // this.getGoods()
        this.getAllGoods()
        this.getSpeedRatio() // 速比
        this.getFlange() // 法兰
        this.getColor() // 颜色
        this.getClient() // 颜色
		// this.getAccount() // 账号
		// this.getMonth()
	},
	methods: {
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		//表单提交方法
		submit(e) {
            this.form.is_check = e
            let price = true;
            let sale_num = true;
            let customer_id = true;
            let array = [];
            let price_error_rows = [];
            let sale_num_error_rows = [];
            let customer_id_error_rows = [];
            this.order_detail.map((item, index) => {
                console.log(index);
                if (item.price <= 0) {
                    price = false;
                    price_error_rows.push(index);
                }
                if (item.sale_num <= 0) {
                    sale_num = false;
                    sale_num_error_rows.push(index);
                }
                if (item.customer_id === '') {
                    customer_id = false;
                    customer_id_error_rows.push(index);
                }
                array.push({
                    id: item.id,
                    goods_model: item.goods_model,
                    speed_ratio_id: item.speed_ratio_id,
                    flange_id: item.flange_id,
                    color_id: item.color_id,
                    price: item.price,
                    sale_num: item.sale_num,
                    hole: item.hole,
                    total_price: item.total_price,
                    customer_id: item.customer_id,
                    remark1: item.remark1,
                    remark2: item.remark2
                });
            });
            this.form.order_detail = array;
            if (!price) {
                let errorMsg = "产品单价不可为0,请检查以下行: ";
                price_error_rows.forEach((row) => {
                    errorMsg += row+1 + ",";
                });
                this.$message.error(errorMsg);
            } else if (!sale_num) {
                let errorMsg = "产品数量不可为0,请检查以下行: ";
                sale_num_error_rows.forEach((row) => {
                    errorMsg += row+1 + ",";
                });
                this.$message.error(errorMsg);
            } else if (!customer_id) {
                let errorMsg = "存在未选择客户列,请检查以下行: ";
                customer_id_error_rows.forEach((row) => {
                    errorMsg += row+1 + ",";
                });
                this.$message.error(errorMsg);
            }else{
                this.$refs.dialogForm.validate(async (valid) => {
                    if (valid) {
                        this.isSaveing = true;
                        var res = [];
                        if (this.form.id) {
                            res = await this.$API.contract.contract.edit.post(this.form);
                        } else {
                            res = await this.$API.contract.contract.add.post(this.form);
                        }
                        this.isSaveing = false;
                        if (res.code == 1) {
                            this.visible = false;
                            this.$emit('success', this.form, this.mode)
                            this.$message.success("操作成功")
                        } else {
                            this.$alert(res.message, "提示", { type: 'error' })
                        }
                    } else {
                        return false;
                    }
                })
            }
		},
		//表单注入数据
		async setData(data) {
            this.form.id = data.id
            var res = await this.$API.contract.contract.detail.get({id:data.id});
            this.form.seller_id = res.data.seller_id
            this.form.open_single = res.data.open_single
            this.form.contract_code = res.data.contract_code
            let array = []
            res.data.order_detail.map(item=>{
                array.push({
                    id:item.id,
                    goods_model:item.goods_model,
                    sale_num:item.sale_num,
                    price:item.price,
                    total_price:item.total_price,
                    speed_ratio_id:item.speed_ratio_id?item.speed_ratio_id:'',
                    flange_id:item.flange_id?item.flange_id:'',
                    color_id:item.color_id?item.color_id:'',
                    hole:item.hole,
                    customer_id:item.customer_id,
                    remark1:item.remark1,
                    remark2:item.remark2,
                    speedList: item.all_options[0].speed_ratios,
                    flangeList: item.all_options[0].flanges,
                    colorList: item.all_options[0].colors,
                    
                })
            })
            this.order_detail = array
            this.totalCompute()
		},
        onFocus(event){
            event.target.select();
        },
        // 选择商品
        checkGoods(e){
            this.dialog.goods = true
            this.$nextTick(() => {
                this.$refs.goodsDialog.open('add').setData(e)
            })
        },
        goodsUpdate(data){
            let array = []
            data.map((item)=>{
                array.push({
                    goods_id:item.id,
                    goods_name:item.goods_name,
                    cate_id:item.last_cate,
                    unit_id:item.unit_id,
                    material_code:item.material_code,
                    goods_code:item.goods_code,
                    sale_num: 1,
                    price:item.factory_price,
                    total_price:item.factory_price,
                })
            })
            let existingIds = this.order_detail.map(item => item.goods_id);
            for(let i = array.length - 1; i >= 0; i--){
                if(existingIds.includes(array[i].goods_id)){
                    array.splice(i, 1);
                }
            }
            this.order_detail = [...this.order_detail,...array]
            this.totalCompute()
        },
        totalCompute() {
            let count_price = 0
            this.form.contract_price = 0
            this.form.total_price = 0
            this.order_detail.map(item => {
                if(item.price && item.sale_num){
                    count_price = Number(count_price) + (Number(item.sale_num) * Number(item.price))
                    item.total_price = (Number(item.sale_num) * Number(item.price)).toFixed(0)
                }
            })
            this.form.contract_price = (count_price).toFixed(0)
            this.form.total_price = (count_price).toFixed(2)
		},
        // 获取分类
        async getCate(){
            var res = await this.$API.goods.goodsCate.all.get();
            this.cateList = res.data
        },
        // 获取单位
        async getUnit(){
            var res = await this.$API.goods.goodsUnit.all.get();
            this.unitList = res.data
        },
        // 获取销售人
        async getAdmin(){
            var res = await this.$API.system.admin.all.get();
            this.adminList = res.data;
        },
        // 全部产品
        async getAllGoods(){
            var res = await this.$API.contract.contract.getallproduct.get();
            this.goodsList = res.data;
        },
        // 获取速比
        async getSpeedRatio(){
            var res = await this.$API.common.getDictData.get({ type: "speedRatio" });
            let array = []
            res.data.speedRatio.map(item=>{
                array.push({
                    id:Number(item.id),
                    name:item.name
                })
            })
            this.speedList = array;
        },
        // 获取法兰
        async getFlange(){
            var res = await this.$API.common.getDictData.get({ type: "flange" });
            let array = []
            res.data.flange.map(item=>{
                array.push({
                    id:Number(item.id),
                    name:item.name
                })
            })
            this.flangeList = array;
        },
        // 获取速比
        async getColor(){
            var res = await this.$API.common.getDictData.get({ type: "color" });
            let array = []
            res.data.color.map(item=>{
                array.push({
                    id:Number(item.id),
                    name:item.name
                })
            })
            this.colorList = array;
        },
        async getClient(){
            var res = await this.$API.client.client.all.get();
            this.clientList = res.data;
        },
        async goodsChange(row){
            row.speedList = []
            row.flangeList = []
            row.colorList = []
            let data =  this.goodsList.find(item=>{return item.name==row.goods_model})
            var res = []
            if(data.is_product == 1){
                res = await this.$API.contract.contract.getproduct.get({goods_model:row.goods_model});
            }else{
                res = await this.$API.contract.contract.getmater.get({goods_model:row.goods_model});
            }
            if(data.is_product == 1){
                row.speedList = res.data;
            }else{
                if(res.data!='' && res.data[0].exist_speed_ratio == 1){
                    row.speedList = res.data
                }else{
                    row.colorList = res.data;
                }
            }
            row.speed_ratio_id = ''
            row.flange_id = ''
            row.color_id = ''
        },
        async speedChange(row){
            row.flangeList = []
            row.colorList = []
            var res = []
            if(row.speedList !='' && row.speedList[0].exist_speed_ratio ==1  && row.speed_ratio_id !=undefined ){
                res = await this.$API.contract.contract.getmater.get({goods_model:row.goods_model,speed_ratio_id:row.speed_ratio_id});
                row.colorList = res.data
            }else{
                res = await this.$API.contract.contract.getproduct.get({goods_model:row.goods_model,speed_ratio_id:row.speed_ratio_id});
                row.flangeList = res.data;
            }
            row.flange_id = ''
            row.color_id = ''
        },
        async flangeChange(row){
            var res = await this.$API.contract.contract.getproduct.get({goods_model:row.goods_model,speed_ratio_id:row.speed_ratio_id,flange_id:row.flange_id});
            row.color_id = ''
            if(Array.isArray(res.data)){
                row.colorList = res.data
            }else{
                row.hole = res.data.name
                var sub = await this.$API.contract.contract.getprice.get({goods_model:row.goods_model,speed_ratio_id:row.speed_ratio_id,flange_id:row.flange_id});
                row.price = sub.data.sell_price
                if(row.sale_num){
                    row.total_price = row.sale_num * row.price
                }
                this.totalCompute()
            }
        },
        async colorChange(row){
            var res = await this.$API.contract.contract.getproduct.get({goods_model:row.goods_model,speed_ratio_id:row.speed_ratio_id,flange_id:row.flange_id,color_id:row.color_id});
            row.hole = res.data.name
            var sub = await this.$API.contract.contract.getprice.get({goods_model:row.goods_model,speed_ratio_id:row.speed_ratio_id,flange_id:row.flange_id,color_id:row.color_id});
            row.price = sub.data.sell_price
            if(row.sale_num){
                row.total_price = row.sale_num * row.price
            }
            this.totalCompute()
        },
        remarkInput(row){
            if(row.remark1 !=''){
                row.price = ''
                row.total_price = ''
            }
        },
        // 账户
		async getAccount() {
			var res = await this.$API.finance.account.all.get();
			this.accountList = res.data;
		},
		getMonth() {
			for (let i = 1; i < this.stages_all.length; i++) {
				let prevDate = this.moment(this.stages_all[i - 1].collect_date);
				let nextDate = prevDate.add(1, 'month');
				this.stages_all[i].collect_date = nextDate.format('YYYY-MM-DD');
			}
		},
		stageInput(row, index) {
			// this.setStage(row,index)
			let num = 0
			this.stages_all.map((item, index1) => {
				if (index1 <= index) {
					num += item.money
				}
				if (index1 == index + 1) {
					item.money = this.form.total_price - Number(num)
				}
			})
		},
		setStage(row, index) {
			let num = 0
			this.stages_all.map((item, index1) => {
				if (index1 <= index) {
					num += item.money
				}
				if (index1 == index + 1) {
					item.money = this.form.total_price - Number(num)
				}
			})
		},
		stageInputRate(row, index) {
			let num = 0
			this.stages_all.map((item, index1) => {
				if (index1 <= index) {
					num += item.collect_rate
					// item.money = (this.form.total_price * num / 100).toFixed(2)
				}
				if (index1 == index + 1) {
					item.collect_rate = 100 - Number(num)
					// item.money = index == 0 ? this.form.total_price - this.stages_all[index].money : this.stages_all[index - 1].money - this.stages_all[index].money
				}
			})
		},
		closeStage() {
			this.stage = false
			let array = []
			this.stages_all.map(item => {
				if (item.money != 0) {
					array.push({
						collect_rate: item.collect_rate,
						money: item.money,
						stages_number: item.stages_number,
						collect_date: item.collect_date,
						remark: item.remark,
					})
				}
			})
			this.form.stages_all = array
		},
		openStage() {
			this.stage = true
			if (this.mode == 'add' || this.mode == 'copy') {
				this.stages_all[0].money = this.form.total_price
			}
		},
	}
}
</script>

<style></style>
